package com.xiaoluyy.rpc.proxy;



import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RpcClientProxy<T> implements InvocationHandler {
    private final Class<T> proxyInterface;
    private ApplicationContext applicationContext;

    public RpcClientProxy(Class<T> proxyInterface, ApplicationContext applicationContext) {
        this.proxyInterface = proxyInterface;
        this.applicationContext = applicationContext;
    }


    public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {

        System.out.println("当前执行了方法");
        if (!Object.class.equals(method.getDeclaringClass()) && !method.isDefault()) {
            // DataParser dataParser = DataParser.newInstance(method, args);
            // Class<?> returnType = dataParser.getReturnType();
            // String systemCode = dataParser.getSystemCode();
            //
            // String serviceName = dataParser.getServiceName();
            // String serviceMethod = dataParser.getServiceMethod();
            String serviceMethod = "sendTextSms$8";
            Object smsServiceClient = applicationContext.getBean("smsServiceClient");
            Method serviceMethod1 = smsServiceClient.getClass().getDeclaredMethod(serviceMethod,String.class,args[0].getClass());
            Object invoke = serviceMethod1.invoke(smsServiceClient, args);
            //  参数解析
            System.out.println(invoke);
            return invoke;
        } else {
            return method.invoke(this, args);
        }
    }
    public T newProxyInstance() {
        ClassLoader classLoader = this.proxyInterface.getClassLoader();
        Class<?>[] interfaces = new Class[]{this.proxyInterface};
        return (T) Proxy.newProxyInstance(classLoader, interfaces, this);
    }
}

